package com.wqh.conformity.jwt.controller;

import com.alibaba.fastjson.JSONObject;
import com.wqh.conformity.jwt.config.JwtConfig;
import com.wqh.conformity.jwt.domain.Result;
import com.wqh.conformity.jwt.domain.User;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author wqh
 */
@RestController
public class TestController {

    @Resource
    private JwtConfig jwtConfig;

    /**
     * 用户登录接口
     *
     * @param userName
     * @param passWord
     * @return
     */
    @PostMapping("/login")
    public Result<?> login(@RequestParam("userName") String userName,
                           @RequestParam("passWord") String passWord) {
        JSONObject json = new JSONObject();

        User user = new User();
        user.setUserId(1L);
        user.setUsername(userName);
        user.setPassword(passWord);
        String token = jwtConfig.createToken(JSONObject.toJSON(user).toString());
        if (!StringUtils.isEmpty(token)) {
            json.put("token", token);
        }
        return Result.ok(json);
    }

    /**
     * 需要 Token 验证的接口
     */
    @PostMapping("/info")
    public Result<?> info() {
        return Result.ok("info");
    }

    /**
     * 根据请求头的token获取userId
     * @param request
     */
    @GetMapping("/getUserInfo")
    public Result<?> getUserInfo(HttpServletRequest request) {
        String usernameFromToken = jwtConfig.getUsernameFromToken(request.getHeader("token"));
        return Result.ok(JSONObject.parseObject(usernameFromToken, User.class));
    }
}
